import { PageContainer, ProTable } from "@ant-design/pro-components";
import {
  Button,
  Modal,
  Input,
  InputNumber,
  Form,
  Radio,
  Space,
  Popconfirm,
  Checkbox,
  Select,
  message,
  Switch,
} from "antd";
import { connect, history } from "umi";
import { namespace, calcColumns } from "./configFile";
import { useEffect, useRef, useState } from "react";
import styles from "./styles.less";
import { PlusOutlined } from "@ant-design/icons";
import Https from "@/utils/Https";
const Page = (props) => {
  const { dispatch, submitLoading, venueArr, labelArr } = props;
  const [open, setOpen] = useState(false);
  const [titleType, setTitleType] = useState(0);
  const [venueName, setVenueName] = useState("");
  const [dataTotal, setDataTotal] = useState(0);
  const [form] = Form.useForm();
  const actionRef = useRef();
  // useEffect(() => {
  //   dispatch({
  //     type: `${namespace}/pageInit`,
  //   });
  // }, []);

  const editInfo = (params) => {
    setOpen(true);
    setTitleType(1);
    form.setFieldsValue({
      ...params,
      roomFacility: params.roomFacility ? params.roomFacility.split(",") : [],
    });
    let venueList = venueArr.filter(function (o) {
      return o.id == params.venueId;
    });
    let newVenueName = venueList.length > 0 ? venueList[0].venueName : "";
    setVenueName(newVenueName);
  };
  const getList = async (params) => {
    let records = [];
    let total = 0;
    let res = await Https.post("/venue/classroom/roomList", params, true);
    if (res.code == 200) {
      records = res.data.records;
      total = res.data.total;
    } else {
      message.error(res.msg);
    }
    setDataTotal(total);
    return {
      success: true,
      data: records,
      total,
    };
  };
  const toggleState = async (params) => {
    let res = await Https.post("/venue/classroom/updateStatus", params, true);
    if (res.code == 200) {
      message.success("操作成功");
      actionRef.current && actionRef.current?.reload();
    } else {
      message.error(res.msg);
    }
  };

  const deleteItem = (params) => {
    dispatch({
      type: `${namespace}/deleteItem`,
      params,
      callback: () => {
        actionRef.current?.reload();
      },
    });
  };

  const operate = [
    {
      title: "状态",
      dataIndex: "roomStatus",
      render: (id, record) => {
        return (
          <Switch
            checkedChildren="启用"
            unCheckedChildren="禁用"
            value={record.roomStatus == "0" ? true : false}
            onChange={() => {
              toggleState({ id: record.id });
            }}
          />
        );
      },
    },
    {
      title: "操作",
      fixed: "right",
      dataIndex: "operate",
      align: "center",
      hideInSearch: true,
      width: 100,
      render: (id, record) => {
        return (
          <Space>
            <Button type="link" onClick={() => editInfo(record)}>
              编辑
            </Button>
            {/* <Popconfirm
              title="确定要删除该教室吗?"
              onConfirm={() => deleteItem({ id: record.id })}
            >
              <Button type="link" danger>
                删除
              </Button>
            </Popconfirm> */}
          </Space>
        );
      },
    },
  ];

  const submitForm = async () => {
    const res = await form.validateFields();
    if (res) {
      dispatch({
        type: `${namespace}/submitItem`,
        params: {
          ...res,
          courseType: res.courseType.toString(),
          roomFacility:
            res.roomFacility && res.roomFacility.length > 0
              ? res.roomFacility.toString()
              : "",
        },
        callback: () => {
          setOpen(false);
          actionRef.current?.reload();
        },
      });
    }
  };

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        toolBarRender={() => [
          <>
            <Button
              disabled={dataTotal == 0}
              onClick={() => {
                history.push("/stadium/classroom/occupy");
              }}
            >
              占用时间
            </Button>
            <Button
              icon={<PlusOutlined />}
              type="primary"
              onClick={() => {
                form.resetFields();
                setTitleType(0);
                setOpen(true);
              }}
            >
              新增教室
            </Button>
          </>,
        ]}
        //scroll={{ x: 1500 }}
        request={async (params) => {
          return await getList(params);
        }}
        pagination={{
          showSizeChanger: true,
        }}
        columns={calcColumns({ operate, venueArr, labelArr })}
      />

      <Modal
        open={open}
        title={titleType ? "编辑教室" : "新增教室"}
        forceRender
        width="50%"
        onCancel={() => setOpen(!open)}
        wrapClassName={styles.roomForm}
        footer={
          <Space>
            <Button onClick={() => setOpen(false)}>取消</Button>
            <Button onClick={submitForm} loading={submitLoading} type="primary">
              确定
            </Button>
          </Space>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ containPeopleNum: 1 }}
        >
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>

          <Form.Item
            label="教室名称"
            name="classRoomName"
            rules={[{ required: true, message: "教室名称不能为空" }]}
          >
            <Input maxLength={20} placeholder="请输入,限20个字" showCount />
          </Form.Item>
          <Form.Item
            label="可容纳人数"
            name="containPeopleNum"
            rules={[{ required: true, message: "可容纳人数不能为空" }]}
          >
            <InputNumber min={1} max={100} style={{ width: "100%" }} />
          </Form.Item>
          {/* {titleType == 0 && (
            <Form.Item
              label="所属场馆"
              name="venueId"
              rules={[{ required: true, message: "所属场馆不能为空" }]}
            >
              <Radio.Group>
                {venueArr.map((v) => (
                  <Radio value={v.id}>{v.venueName}</Radio>
                ))}
              </Radio.Group>
            </Form.Item>
          )}
          {titleType == 1 && (
            <Form.Item
              label="所属场馆"
              name="venueId"
              rules={[{ required: true, message: "所属场馆不能为空" }]}
            >
              {venueName}
            </Form.Item>
          )} */}
          <Form.Item
            label="适用课程类型"
            name="courseType"
            rules={[{ required: true, message: "适用课程不能为空" }]}
          >
            <Checkbox.Group>
              <Checkbox value="1">私教课</Checkbox>
              <Checkbox value="2">团课</Checkbox>
              <Checkbox value="3">班课</Checkbox>
            </Checkbox.Group>
          </Form.Item>
          <Form.Item label="教室设施" name="roomFacility">
            <Select mode="multiple">
              {labelArr &&
                labelArr.map((e: { id: string; facilityName: string }) => (
                  <Select.Option key={e.id} value={e.id}>
                    {e.facilityName}
                  </Select.Option>
                ))}
            </Select>
          </Form.Item>
          <Form.Item label="备注" name="remark">
            <Input.TextArea
              placeholder="请输入"
              rows={4}
              showCount
              maxLength={300}
            />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default connect((state) => ({
  ...state[namespace],
  submitLoading: state.loading.effects[`${namespace}/submitItem`],
}))(Page);
